package com.sugon.optional;

import org.junit.Test;

import java.util.Optional;


/**
 *
 * 一般用来解决空指针异常
 * 创建Optional
 * empty()  创建空值
 * of(T value) 创建非空值
 * ofNullable(T value) 创建Optional对象, 允许null值
 *
 * 访问Optional
 * isPresent():  判断值是否存在
 * get()  获取值, 空值抛异常
 * orElse(T value) 获取值, 如果无值则取默认值
 * ifPresent(Consumer<T> con) 如果值存在, 则消费值
 *
 * @author LUOYUAN
 * @date 2018-12-08-18:56
 */
public class TestOptional {
    public static void main(String[] args) {
        Man man = new Man();

        //不用做为空判断直接调用
        //man.wife.ifPresent(t->t.menthod());
        //方法引用表达
        man.wife.ifPresent(Woman::menthod);

    }

    @Test
    public void test(){
        Optional<String> o1 = Optional.ofNullable("ABC");
        Optional<String> o2 = Optional.ofNullable(null);
    	System.out.println(o1.isPresent());
    	System.out.println(o2.isPresent());

    	String s1 = o1.get();
    	System.out.println(s1);
    	//String s2 = o2.get();
    	System.out.println(o1.orElse("hello"));

    	//没有值则取默认值
    	System.out.println(o2.orElse("hello"));

    	o1.ifPresent(t->System.out.println(t));

    	//如果存在值则消费
    	o2.ifPresent(System.out::println);
    }
}

